package com.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//拦截器拦截token校验
public class TokenIntercepter implements HandlerInterceptor {

    private Logger logger= LoggerFactory.getLogger(TokenIntercepter.class);

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //验证token,在前端从请求头拿token
        String token = request.getHeader("token");
        logger.info("请求头的token"+token);
        //System.out.println("请求头的token"+token);
        if(StringUtils.isEmpty(token)){
            write(response,"请求头不存在");
            return false;
        }
        //从token生成userName和password
       String userName=  JWTSignalUtils.getTokenValue(token,"userName");
        String password=  JWTSignalUtils.getTokenValue(token,"password");
        logger.info("存在redis的token的KEY"+Constants.userTokenInfo+userName+password);
        //Constants.userRedisConstants+u.getUserName()+u.getPassword()
         Object mytoken=redisUtil.get(Constants.userTokenInfo+userName+password);

        logger.info("存在redis的token"+(String)mytoken);
        if(StringUtils.isNull(mytoken)){
            write(response,"请求头不存在");
            return false;
        }else if(!token.equals((String)mytoken) ){
            logger.info("存在redis的token"+(String)mytoken);
            write(response,"请求头不一致");
            return false;
        }else{
            logger.info("存在redis的token"+(String)mytoken+"二者相等放行");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
   //此所以让l拦截器被拦截者返回有值也
    private void write(HttpServletResponse response,String msg){
        JSONObject jsonObject = new JSONObject();
        PrintWriter out = null;
        response.setStatus(HttpStatus.ERROR);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        jsonObject.put("code", "500");
        jsonObject.put("msg", msg);
        jsonObject.put("data", "");
        try{
            out = response.getWriter();
            out.println(jsonObject);
        }catch (Exception e){

        }finally {
            out.close();
        }
    }
}
